package com.youdianstar.app.util

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.CompoundButton
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox

import com.youdianstar.app.R
import com.youdianstar.app.support.imp.ICardPayListener
import com.youdianstar.app.common.ex.setThrottleListener
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.Extra
import com.youdianstar.app.ui.web.WebActivity
import com.youdianstar.app.common.ex.setAgreementLine
import com.youdianstar.app.common.util.LanguageConfig
import com.stripe.android.view.CardInputWidget
import java.util.Locale
import com.youdianstar.app.common.auko.startActivity

/**
 * File: SheetPaymentDialog
 * Author: 82149 Create: 2021/11/27 16:41
 * Changes (from 2021/11/27)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class SheetPaymentDialog(val bisType:Int,val isShowBind:Boolean,val listener: ICardPayListener) : BottomSheetDialogFragment() {
    private var rootView: View? = null
    private var cardInput:CardInputWidget?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialogBg)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.sheet_pay_card, container)
        setView()
        return rootView
    }
    /**
     * 更新扫卡卡号
     * @param pin 卡号
     */
    fun setScanNumber(pin:String){
        if (pin.isNotEmpty())
            cardInput?.setCardNumber(pin)
    }

    private fun setView() {
        val ivClose = rootView?.findViewById<ImageView>(R.id.ic_cancel)
        val ivScan = rootView?.findViewById<ImageView>(R.id.iv_scan)
        cardInput = rootView?.findViewById(R.id.cardInput)

        val tvBind = rootView?.findViewById<TextView>(R.id.tv_add_content)
        val boxBind = rootView?.findViewById<AppCompatCheckBox>(R.id.box_add)

        val llAgreement = rootView?.findViewById<LinearLayout>(R.id.ll_agreement)
        val tvContent = rootView?.findViewById<TextView>(R.id.tv_agree_content)
        val boxAgreement = rootView?.findViewById<AppCompatCheckBox>(R.id.box_term)
        val btnPay = rootView?.findViewById<TextView>(R.id.btn_pay)

        boxBind?.visibility = if (isShowBind) View.VISIBLE else View.GONE
        tvBind?.visibility = if (isShowBind) View.VISIBLE else View.GONE

        if (bisType == BisType.Bis_Deposit){
            tvContent?.let { v ->
                setAgreementLine(v, part1Tx = getString(R.string.login_agreeTo)+" ",
                    String.format(getString(R.string.login_TxContent),getString(R.string.login_depositAgreement)),"")
            }
            llAgreement?.visibility = View.VISIBLE
        }

        cardInput?.postalCodeEnabled = true
        cardInput?.postalCodeRequired = true

        ivClose?.setThrottleListener {
            dialog?.dismiss()
        }
        ivScan?.setThrottleListener {
            listener.onScanBankcard()
        }
        tvBind?.setOnClickListener {
            val isBind = boxBind?.isChecked ?: false
            boxBind?.isChecked = !isBind
        }

        //支付协议
        tvContent?.setThrottleListener {
            val language = LanguageConfig.instance.getLanguageCode().uppercase(Locale.ROOT)
            val urlTx = DataAppManager.instance.getConfig(ConfigKey.CONFIG_DEPOSIT_URL)+"?lang="+language
            val titleTx = getString(R.string.login_depositAgreement)
            requireActivity().startActivity<WebActivity>(Extra.IT_DATA to urlTx, Extra.IT_NOTIFY to titleTx)
        }

        boxAgreement?.isChecked = true
        boxAgreement?.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(button: CompoundButton?, isCheck: Boolean) {
                btnPay?.isEnabled = isCheck
            }
        })
        btnPay?.isEnabled = true
        btnPay?.setThrottleListener {
            val isBind = boxBind?.isChecked ?: false
            cardInput?.cardParams?.let {
                listener.onPaymentByCard(it, cardInput!!.paymentMethodCreateParams, isBind, default = false)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        //拿到系统的 bottom_sheet
        val view: FrameLayout = dialog?.findViewById(R.id.design_bottom_sheet)!!
        //设置view高度
        view.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
        //获取behavior
        val behavior = BottomSheetBehavior.from(view)
        //设置弹出高度
        behavior.peekHeight = 2800
        //设置展开状态
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        behavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_EXPANDED -> {
                    }
                    BottomSheetBehavior.STATE_COLLAPSED -> {
                    }
                    BottomSheetBehavior.STATE_DRAGGING -> {
                    }
                    BottomSheetBehavior.STATE_SETTLING -> {
                    }
                    BottomSheetBehavior.STATE_HIDDEN -> {
                    }
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {

            }

        })
    }

    override fun onCancel(dialog: DialogInterface) {
        dialog.dismiss()
        super.onCancel(dialog)
    }

    override fun dismiss() {
        hideKeyBoard()
        super.dismiss()
    }

    /**
     * dialog中 关闭软键盘
     */
    private fun hideKeyBoard() {
        context?.let { patent ->
            val imm = patent.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val view = dialog?.window?.currentFocus
            view?.let {
                imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }


}